package com.fj.netty.chat.serializer;

import com.fj.netty.chat.message.Message;
import com.google.gson.Gson;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author fj
 * @date 2024/1/16 16:26
 */
public interface Serializer {
    <T> byte[] serialize(T obj);
    <T> T deserialize(byte[] bytes, Class<T> clz);

    enum Algorithm implements Serializer{
        JAVA{
            @Override
            public <T> byte[] serialize(T obj) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                try {
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
                    objectOutputStream.writeObject(obj);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                return byteArrayOutputStream.toByteArray();
            }

            @Override
            public <T> T deserialize(byte[] bytes, Class<T> clz) {
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
                try {
                    ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
                    return (T) objectInputStream.readObject();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        },
        JSON{
            @Override
            public byte[] serialize(Object obj) {
                return new Gson().toJson(obj).getBytes(StandardCharsets.UTF_8);
            }

            @Override
            public <T> T deserialize(byte[] bytes, Class<T> clz) {
                return new Gson().fromJson(new String(bytes, StandardCharsets.UTF_8), clz);
            }
        }
    }
}
